package com.gitee.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.bo.AdminRoleBo;
import com.gitee.mapper.AdminRoleMapper;
import com.gitee.pojo.AdminRole;
import com.gitee.service.IAdminRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements IAdminRoleService {

    /**
     * 根据后台用户id删除用户关联角色
     * @param adminId
     * @return
     */
    @Transactional
    @Override
    public Boolean deleteByAdminId(Integer adminId) {
        LambdaUpdateWrapper<AdminRole> updateWrapper = new UpdateWrapper<AdminRole>().lambda().eq(AdminRole::getAdminId, adminId);
        return super.remove(updateWrapper);
    }

    /**
     * 根据后台用户id更新用户角色
     *
     * @param adminId
     * @return
     */
    @Transactional
    @Override
    public Boolean updateByAdminId(Integer adminId, AdminRoleBo adminRoleBo) {
        deleteByAdminId(adminId);
        List<AdminRole> adminRoles = adminRoleBo.getRoleIds().stream().map(roleId -> {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            return adminRole;
        }).collect(Collectors.toList());
        return super.saveBatch(adminRoles);
    }

    /**
     * 根据后台用户id删除用户关联角色
     *
     * @param adminIds
     * @return
     */
    @Override
    public Boolean deleteByAdminIds(Integer[] adminIds) {
        LambdaUpdateWrapper<AdminRole> updateWrapper = new UpdateWrapper<AdminRole>().lambda().in(AdminRole::getAdminId, Arrays.asList(adminIds));
        return super.remove(updateWrapper);
    }
}
